package com.yequan.work;


import java.util.Map;

/**
 * 架构重构灰度工具
 *
 * @author yequan
 * @date 2021/10/25 16:45
 **/
public class GrayscaleUtil {

    public static String ALL_CLOSE = "-1";
    public static String ALL_OPEN = "99";

    public static void main(String[] args) {
        System.out.println(grayscaleByUserId(228901, ""));
    }

    /**
     * 支持 userId 尾号灰度,灰度比例
     * {
     * "cut_ratio": 10,
     * "open_ratio": 100
     * }
     *
     * @param userId
     * @param grayscale
     * @return
     */
    private static boolean grayscaleByUserId(Integer userId, String grayscale) {
//        if (ALL_CLOSE.equals(grayscale)) {
//            return false;
//        }
//        if (ALL_OPEN.equals(grayscale)) {
//            return true;
//        }
//        Map<String, Object> grayscaleMap = JsonMapper.json2Map(grayscale);
        int cutRatio = 100;
        int openRatio = 1;
        int suffixLength = getSuffixLength(cutRatio);
        int lastNum = Integer.parseInt(userId.toString().substring(userId.toString().length() - suffixLength));

        if (openRatio == 0) {
            return false;
        }
        if (openRatio == 100) {
            return true;
        }
        float pivotNum = cutRatio * (openRatio / 100.0f);
        if (lastNum < pivotNum) {
            return true;
        }
        return false;
    }

    private static int getSuffixLength(int cutRatio) {
        int suffixLength = 2;
        switch (cutRatio) {
            case 10:
                suffixLength = 1;
                break;
            case 100:
                suffixLength = 2;
                break;
            case 1000:
                suffixLength = 3;
                break;
            case 10000:
                suffixLength = 4;
                break;
            default:
        }
        return suffixLength;
    }
}